package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.MessageConstant;
import com.itheima.dao.CheckItemDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.CheckItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author zz
 */ //解决老版本下开启事务暴露接口不正确的问题
@Service(interfaceClass = CheckItemService.class)
@Transactional
public class CheckItemServiceImpl implements CheckItemService{

    @Autowired
    private CheckItemDao checkItemDao;
    @Override
    public Result AddCheckItem(CheckItem checkItem) {
        //调用具体dao里面的方法 进行增加
        boolean b = checkItemDao.addCheckItem(checkItem);
        if (b){
            Result result = new Result(true, MessageConstant.ADD_CHECKITEM_SUCCESS);
            return  result;
        }
        return new Result(false,MessageConstant.ADD_CHECKITEM_FAIL);
    }
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Page<Object> page = PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        List<CheckItem> checkItems = checkItemDao.findPage(queryPageBean);
        return new PageResult(page.getTotal(),checkItems);
    }
    @Override
    public CheckItem findById(Integer id) {
        CheckItem checkItem = checkItemDao.findById(id);
        return checkItem;
    }
    @Override
    public void update(CheckItem checkItem) {
        checkItemDao.update(checkItem);
    }

    @Override
    public List<CheckItem> findAll() {
       return checkItemDao.findAll();
    }

    @Override
    public Result deleteCheckItem(Integer id) {
        //先判断这个id是其他的表中是否存在
        int count = checkItemDao.findCount(id);
        //其他的表 什么表
        if (count==0){
            boolean flag = checkItemDao.deleteCheckItem(id);
            return new Result(flag, MessageConstant.DELETE_CHECKITEM_SUCCESS);
        }
        //删除中间表的数据
        boolean b = this.deletet_checkgroup_checkitem(id);
        if (b){
            boolean b1 = checkItemDao.deleteCheckItem(id);
            if (b1) {
                return new Result(b1, MessageConstant.DELETE_CHECKITEM_SUCCESS);
            }
        }
        return new Result(false, MessageConstant.DELETE_CHECKITEM_FAIL);
    }

    @Override
    public boolean deletet_checkgroup_checkitem(Integer id) {
        boolean b = checkItemDao.delete_checkgroup_checkitem(id);
        return b;
    }
}

